<?php
/**
* 微信支付 model
*/
class WxPay_model extends MY_Model
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('Curl_model','curl');
		$this->load->model('Weixin_model','wx');
  		$this->appid='wx554ae3d8bd178aef';
  		$this->appsecret='f61e29965170fa0816e470aeed345b03';
  		$this->mchid='1249935801';
  		$this->mchkey='huiyouxinghuiyouxinghuiyouxinghu';
	}

	/**
	 * 1、刷卡支付
	 */
	function cardPay(){
		$payUrl="https://api.mch.weixin.qq.com/pay/unifiedorder";
	}

	/**
	 * 2、扫码支付
	 */
	function scanPay($backurl='',$orderInfo=array()){
		$payUrl="https://api.mch.weixin.qq.com/pay/unifiedorder";

		$nonce_str=$this->wx->getRandom('32');
		$parameArr=array(
				'appid' => ($this->appid),
				'mch_id' => ($this->mchid),
				'nonce_str' => $nonce_str,
				'body' => '测试',
				'out_trade_no' => (isset($orderInfo['ordersn'])?$orderInfo['ordersn']:''),
				'total_fee' => '1',
				'spbill_create_ip' => $this->getIP(),
				'notify_url' => $backurl,
				'trade_type' => 'NATIVE',
				'product_id' => '1',
			);
		$sign=$this->getSign($parameArr);
		$parameArr['sign']=strtoupper(md5($sign));
		$xmlArr = $this->xml_encode($parameArr);
		echo '<pre />';var_dump($xmlArr);exit;
	}

	/**
	 * 3、公众号支付
	 */
	function publicAccountPay($backurl='',$orderInfo=array()){
		$payUrl="https://api.mch.weixin.qq.com/pay/unifiedorder";

		$nonce_str=$this->wx->getRandom('32');
		$parameArr=array(
				'appid' => ($this->appid),
				'mch_id' => ($this->mchid),
				'nonce_str' => $nonce_str,
				'body' => ((isset($orderInfo['desc'])&&$orderInfo['desc'])?$orderInfo['desc']:'商品'),
				'out_trade_no' => (isset($orderInfo['ordersn'])?$orderInfo['ordersn']:''),
				'total_fee' => 100,
				'spbill_create_ip' => $this->getIP(),
				'notify_url' => $backurl,
				'trade_type' => 'JSAPI',
				'openid' => (isset($orderInfo['openid'])?$orderInfo['openid']:''),
			);
		$sign=$this->getSign($parameArr);
		$parameArr['sign']=strtoupper(md5($sign));
		$xmlArr = $this->xml_encode($parameArr);
		// echo '<pre />';var_dump($xmlArr);exit;
				
		$result = $this->curl->xmlCurlPost($xmlArr, $payUrl);
		$xmlResult = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
		// echo '<pre />';var_dump($xmlResult);exit;
		return (string)$xmlResult->prepay_id;
	}

	/**
	 * 4、APP支付
	 */
	function appPay($backurl='',$orderInfo=array()){
		$payUrl="https://api.mch.weixin.qq.com/pay/unifiedorder";

		$nonce_str=$this->wx->getRandom('32');
		$parameArr=array(
				'appid' => ($this->appid),
				'mch_id' => ($this->mchid),
				'nonce_str' => $nonce_str,
				'body' => '测试',
				'out_trade_no' => '1234567890',
				'total_fee' => '1',
				'spbill_create_ip' => $this->getIP(),
				'notify_url' => $backurl,
				'trade_type' => 'APP',
				'openid' => '1234567890',
			);
		$sign=$this->getSign($parameArr);
		$parameArr['sign']=strtoupper(md5($sign));
		$xmlArr = $this->xml_encode($parameArr);
		echo '<pre />';var_dump($xmlArr);exit;
				
		$res = $this->curl->xmlCurlPost($xmlArr, $payUrl);
		echo '<pre />';var_dump($res);exit;
	}

	
	/**
	 * 4、APP支付
	 */
	function getIP(){
		$realip='';
		if(isset($_SERVER)){
	        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	            $realip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	        } elseif(isset($_SERVER['HTTP_CLIENT_IP'])) {
	            $realip=$_SERVER['HTTP_CLIENT_IP'];
	        } else {
	            $realip=$_SERVER['REMOTE_ADDR'];
	        }
	    }

	    return $realip;
	}

	/**
	 * 支付jsp
	 */
	function getPayJsp($prepay_id=''){
		$this->load->model('Weixin_model','wx');
		$parame=array(
	            'appId' => ($this->appid),
	            'nonceStr' => $this->wx->getRandom(),
	            'package' => 'prepay_id='.$prepay_id,//微信返回
	            'signType' => 'MD5',
	            'timeStamp' => (string)time(),// timeStamp
	        );
		$parame['paySign'] = strtoupper(md5($this->getSign($parame)));

		// if(isset($parame['timeStamp'])){
  //           $tmpTime=$parame['timeStamp'];
  //           unset($parame['timeStamp']);
  //           $parame['timestamp']=$tmpTime;
  //       }

		// ksort($parame);
		return $parame;
	}

	/**
	 * JS-SDK使用权限签名算法
	 */
	function getSign($parame=array()){
		ksort($parame);

		$parameString='';
		if(!empty($parame)){
			foreach ($parame as $key => $value) {
				$parameString.='&'.$key.'='.$value;
			}
		}

		if($parameString){
			$parameString=mb_substr($parameString,1).'&key='.($this->mchkey);
		}
		return $parameString; 
	}

	/**
	 * XML编码
	 * @param mixed $data 数据
	 * @param string $root 根节点名
	 * @param string $item 数字索引的子节点名
	 * @param string $attr 根节点属性
	 * @param string $id   数字索引子节点key转换的属性名
	 * @param string $encoding 数据编码
	 * @return string
	*/
	public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
		if(is_array($attr)){
		    $_attr = array();
		    foreach ($attr as $key => $value) {
		        $_attr[] = "{$key}=\"{$value}\"";
		    }
		    $attr = implode(' ', $_attr);
		}
		$attr   = trim($attr);
		$attr   = empty($attr) ? '' : " {$attr}";
		$xml   = "<{$root}{$attr}>";
		$xml   .= self::data_to_xml($data, $item, $id);
		$xml   .= "</{$root}>";

		return $xml;
	}

	/**
	 * 数据XML编码
	 * @param mixed $data 数据
	 * @return string
	 */
	public static function data_to_xml($data) {
	    $xml = '';
	    foreach ($data as $key => $val) {
	        is_numeric($key) && $key = "item id=\"$key\"";
	        $xml    .=  "<$key>";
	        $xml    .=  ( is_array($val) || is_object($val)) ? self::data_to_xml($val)  : self::xmlSafeStr($val);
	        list($key, ) = explode(' ', $key);
	        $xml    .=  "</$key>";
	    }
	    return $xml;
	}

	/**
	 * 数据XML编码
	 * @param mixed $data 数据
	 * @return string
	 */
	public static function xmlSafeStr($str)
	{
		return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
		// return $str;
	}
}
